
var __wx_f_prefix = "__wx_f_";
var __wx_f_localStorageName = (__wx_f_prefix||"__wx__") + "stay";

// 记录页面停留时间
var __wx_f_second = 0;
var __wx_f_second_interval = window.setInterval(function(){
	__wx_f_second ++;
},1000);


/**
 * 进入页面 
 * 保存localStorage （in、stap-visiable）
 * @return {[type]} [description]
 */
window.onload = function(){
	var data = {
		'type': 'in',
		'time': Date.parse(new Date()),
		'refer': getReferrer(),
		'url': window.location.href,
	}
	setLocalStorgeLog(data);
	var data2 = {
		'type': 'stap',
		'url': this.location.href,
		'time': Date.parse(new Date()),
		'isHidden': document[hiddenProperty]
	};
	setLocalStorgeLog(data2);
}

/**
 * onbeforeunload事件在即将离开当前页面（刷新或关闭）时触发。
 * 保存localStorage out
 * 发送给日志服务器保存浏览数据\并清空localStorage
 * @return {[type]} [description]
 */
window.onbeforeunload = function(){
	var data = {
		'type': 'out',
		'url': this.location.href,
		'stapTime': __wx_f_second,
		'time': Date.parse(new Date()) 
	};
	setLocalStorgeLog(data);

	// send messge Ajax...
	// clear
	window.localStorage[__wx_f_localStorageName || "__wx_f_stap"] = "[{}]";
}

/**
 * 页面可见性 （有兼容性。注：visibilitychange）
 * 记录页面显示状态 探测用户浏览情况
 * [hiddenProperty description]
 * @type {String}
 */
var hiddenProperty = 'hidden' in document ? 'hidden' :    
    'webkitHidden' in document ? 'webkitHidden' :    
    'mozHidden' in document ? 'msHidden' : 'msHidden' in document ? 'msHidden' :    
    null;   
var visibilityChangeEvent = hiddenProperty.replace(/hidden/i, 'visibilitychange');
document.addEventListener(visibilityChangeEvent, function(){
	var isHidden = document[hiddenProperty];
	
	// 隐藏时 停止页面停留时间，可见状态下重启计时
	if(isHidden){
		clearInterval(__wx_f_second);
	}else{
		__wx_f_second_interval = window.setInterval(function(){
			__wx_f_second ++;
		},1000);
	}

	var data = {
		'type': 'stap',
		'url': this.location.href,
		'time': Date.parse(new Date()),
		'isHidden': isHidden
	};
	setLocalStorgeLog(data); 
}, false);

// 设置localStorage数据
function setLocalStorgeLog(data){
	var localStorageName = __wx_f_localStorageName || "__wx_f_stap";
	var stayArr = window.localStorage.getItem(localStorageName) ? window.localStorage.getItem(localStorageName) : '[{}]';
	stayArr = JSON.parse(stayArr);
	stayArr.push(data);
	stayArr = JSON.stringify(stayArr);
	window.localStorage.setItem(localStorageName, stayArr);
}

// 获取用户来路URL （也可以防盗链）
function getReferrer(){
	var referrer = '';
	try{
		referrer = window.top.document.referrer;
	}catch(e){
		try {
            referrer = window.parent.document.referrer;
        } catch(e2) {
            referrer = '';
        }
	}
	if(referrer === '') {
    	referrer = document.referrer;
	}	
	return referrer;
}
